package org.ziegler.javabase.learnEnum;

import java.util.EnumMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public enum Phase {

    SOLID, LIQUID, GAS;

    public enum Transition {
        MELT(SOLID, LIQUID), FREEZE(LIQUID, SOLID),
        BOIL(LIQUID, GAS), CONDENSE(GAS, LIQUID),
        SUBLIME(SOLID, GAS), DEPOSIT(GAS, SOLID),
        ;

        public Phase getFrom() {
            return from;
        }

        public Phase getTo() {
            return to;
        }

        private final Phase from;
        private final Phase to;

        Transition(Phase from, Phase to) {
            this.from = from;
            this.to = to;
        }

//        static {
//            m = Stream.of(values()).collect(Collectors.groupingBy(t -> t.from,
//                    () -> new EnumMap<>(Phase.class),
//                    Collectors.toMap(t -> t.to, t -> t,
//                            (x, y) -> y, () -> new EnumMap<>(Phase.class))));
//        }

        // EnumMap
        private static final Map<Phase, Map<Phase, Transition>> m
                = Stream.of(values()).collect(Collectors.groupingBy(t -> t.from,
                    () -> new EnumMap<>(Phase.class),
                    Collectors.toMap(t -> t.to, t -> t,
                            (x, y) -> y, () -> new EnumMap<>(Phase.class))));

        // HashMap [!!! 这个有问题的，默认创建的不是EnumMap，而是HashMap]
        private static final Map<Phase, Map<Phase, Transition>> m2
                = Stream.of(values()).collect(Collectors.groupingBy(t -> t.from,
                Collectors.toMap(t -> t.to, t -> t)));

        public static Transition of(Phase from, Phase to) {
            return m.get(from).get(to);
        }

        public static Transition of2(Phase from, Phase to) {
            return m2.get(from).get(to);
        }

        public static void printMap() {
            System.out.println(m);
            System.out.println(m2);
        }
    }
}
